package com.easpeed.comon.socket_tool

import android.os.Handler
import android.os.Looper
import android.util.Log
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import okio.ByteString


/**
 * Created by bigyu on 2025-06-26 18:24
 * com.easpeed.comon.socket
 */
class SocketClient {
    private var webSocket: WebSocket? = null
    private var isConnected = false
    private val handler = Handler(Looper.getMainLooper())

    companion object {
        val instance by lazy { SocketClient() }
    }

    private constructor()

    private var url: String? = null
    private val client = OkHttpClient()

    val TAG = "WebSocket"
    fun startClient(url: String) {
        this.url = url
        if (isConnected()) {
            Log.e("WebSocket", "已经连接，请勿重复连接")
            return
        }
        Log.e("WebSocket", "开始连接：$url")

        val request: Request = Request.Builder().url("ws://$url") // 如：192.168.1.100
            .build()
        webSocket = client.newWebSocket(request, object : WebSocketListener() {

            override fun onOpen(webSocket: WebSocket, response: Response) {
                super.onOpen(webSocket, response)
                onConnectChange(true)
                sendLog("连接成功")
                Log.e("WebSocket", "连接成功")
                isConnected = true
                webSocket.send("你好服务端！")
            }

            override fun onMessage(webSocket: WebSocket, text: String) {
                super.onMessage(webSocket, text)
                sendLog("收到服务端消息：$text")
                Log.e("WebSocket", "收到服务端消息：$text")
            }

            override fun onMessage(webSocket: WebSocket, bytes: ByteString) {
                super.onMessage(webSocket, bytes)
            }

            override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
                super.onFailure(webSocket, t, response)
                onConnectChange(false)
                sendLog("连接失败：" + t.message)
                isConnected = false
                Log.e("WebSocket", "连接失败：" + t.message)
            }

            override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
                super.onClosed(webSocket, code, reason)
                sendLog("连接关闭：$reason")
                onConnectChange(false)
                isConnected = false
                Log.e("WebSocket", "连接关闭：$reason")
            }

            override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
                super.onClosing(webSocket, code, reason)
                Log.e("WebSocket", "连接正在关闭：$reason")
            }
        })
    }


    fun sendMsg(msg: String) {
        if (isConnected()) {
            webSocket?.send(msg)
            Log.e("WebSocket", "发送消息：$msg")
        } else {
            Log.e("WebSocket", "未连接，请先连接")
        }
    }

    fun stopClient() {
        if (isConnected()) {
            webSocket?.close(1000, "客户端主动关闭")
            isConnected = false
            webSocket = null
            Log.e("WebSocket", "客户端关闭连接")
        }
    }


    fun onConnectChange(isConnected: Boolean) {
        handler.post {
            onConnectListener?.invoke(isConnected)
        }
    }

    fun sendLog(msg: String?) {
        handler.post {
            onMessageListener?.invoke(msg)
        }
    }

    private var onMessageListener: ((message: String?) -> Unit)? = null
    fun setOnMessageListener(listener: (message: String?) -> Unit) {
        this.onMessageListener = listener
    }

    private var onConnectListener: ((Boolean) -> Unit)? = null

    fun setOnConnectListener(listener: (Boolean) -> Unit) {
        onConnectListener = listener
    }

    fun isConnected(): Boolean {
        return isConnected && webSocket != null
    }

    fun getUrl(): String? {
        return url
    }
}